package cc.yiueil.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Main
 * FixedThreadPool：线程数固定的线程池；
 * CachedThreadPool：线程数根据任务动态调整的线程池；
 * SingleThreadExecutor：仅单线程执行的线程池。
 *
 * @author 弋孓 YIueil@163.com
 * @version 1.0
 * @date 2024/9/24 18:45
 */
public class Main {
    public static void main(String[] args) {
        // 创建固定大小的线程池:
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CustomRunnable runnable1 = new CustomRunnable();
        CustomRunnable runnable2 = new CustomRunnable();
        CustomRunnable runnable3 = new CustomRunnable();
        CustomRunnable runnable4 = new CustomRunnable();
        CustomRunnable runnable5 = new CustomRunnable();
        // 提交任务:
        executor.submit(runnable1);
        executor.submit(runnable2);
        executor.submit(runnable3);
        executor.submit(runnable4);
        executor.submit(runnable5);

        // 停止线程池
        executor.shutdown();

        try {
            // 等待线程池中的所有任务完成
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                // 超时后强制关闭
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 如果等待被中断，也尝试强制关闭
            executor.shutdownNow();
        }
    }
}

class CustomRunnable implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + "---执行中...");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "---执行完成...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
